<?php
/**
 * @todo all of this functionality should be refactored. it is currently a working prototype!
 */
class DigDeveloper_Service_Tool {
    /**
     * tests to determine if the module exists
     * 
     * @param string $name
     */
    public static function moduleExists($name) {
        if(is_dir( self::modulePath($name) )) {
            return true;
        }
    }
    public static function createModule($name) {
        if(self::moduleExists($name)) {
            return false;
        }
        try{
            $config = new stdClass();
            $config->author = DigUser_Service_User::current()->username;
            // create module
            $modulePath = self::modulePath($name);
            mkdir($modulePath);
            // boostrap
            self::createBootsrap($name, $config);
            self::createException($name, $config);
            // create the config
            mkdir($modulePath . '/configs');
            self::createConfig($name);
            mkdir($modulePath . '/controllers');
            mkdir($modulePath . '/forms');
            mkdir($modulePath . '/models');
            mkdir($modulePath . '/views');
            mkdir($modulePath . '/views/scripts');
        } catch (DigDeveloper_Exception $e) {
            // todo handle exception
            return false;
        }
        return true;

    }
    public static function modulePath($name) {
        return APPLICATION_PATH . '/modules/' . $name;
    }
    public static function itemExists($name, $module) {

    }
    public static function createItem($name, $module, $props) {
        if(self::moduleExists($module)) {
            // create the build config file
            $buildFile = self::modulePath($module) . '/configs/build.' . $name . '.ini';
            file_put_contents($buildFile, $props);
            $config = new Zend_Config_Ini($buildFile, null, true);
            $config->author = DigUser_Service_User::current()->username;
            self::createItemController($module, $name, $config);
            self::createForm($module, $name, $config);
            self::createModel($module, $name, $config);
            if(isset($config->item->property)) {
                self::appendItemToConfig($module, $name, ucfirst($name));
            }            
            return true;
        } else {
            $messages[] = 'Critical Error: module does not exist';
        }
    }

    public static function createConfig($module) {
        $configData['title'] = ucfirst($module);
        $config = new Zend_Config($configData);
        $writer = new Zend_Config_Writer_Ini();
        $writer->setConfig($config)
               ->setFilename(self::modulePath($module) . '/configs/module.ini')
               ->write();
    }

    public static function appendItemToConfig($module, $name, $controller) {
//        // I had tons of trouble getting the ini writer to not override the items with this code:
//        $configPath = self::modulePath($module) . '/configs/module.ini';
//        $config = new Zend_Config_Ini($configPath, null, array(
//            'skipExtends'        => true,
//            'allowModifications' => true)
//        );
//        $config->item = array($itemData['name'] => $itemData);
//        $writer = new Zend_Config_Writer_Ini();
//        $writer->setConfig($config)
//               ->setFilename($configPath)
//               ->write();
        $configPath = self::modulePath($module) . '/configs/module.ini';
        $configFile = file_get_contents($configPath);
        $configFile .= PHP_EOL . '; registering ' . $name . ' item ' . PHP_EOL .
            'item.' . $name . '.name = "' . $name . '"' . PHP_EOL .
            'item.' . $name . '.controller = "' . $controller . '"' . PHP_EOL;
        file_put_contents($configPath, $configFile);
    }

    public static function createBootsrap($module, $config) {
        $bootstrap = new Zend_CodeGenerator_Php_Class();
        $bootstrap->setName(ucfirst($module) . '_Bootstrap')
            ->setExtendedClass('Zend_Application_Module_Bootstrap')
            ->setDocblock(new Zend_CodeGenerator_Php_Docblock(array(
               'shortDescription'       => $module . ' bootstrap',
               'longDescription'        => 'This bootstrap file was generated with Digitalus Framework Developer Tools',
                'tags'  => array(
                    array('name' => 'author', 'description' => $config->author)
                )
        )));
        $bootstrapPath = self::modulePath($module) . '/Bootstrap.php';
        $bootstrapFile = '<?php' . PHP_EOL .
            "require_once APPLICATION_PATH . '/modules/" . $module . "/Exception.php';" . PHP_EOL .
            $bootstrap->generate();
        file_put_contents($bootstrapPath, $bootstrapFile);
        return 'Created bootstrap class at: ' . $bootstrapPath;
    }

    public static function createException($module, $config) {
        $exception = new Zend_CodeGenerator_Php_Class();
        $exception->setName(ucfirst($module) . '_Exception')
            ->setExtendedClass('Dig_Exception')
            ->setDocblock(new Zend_CodeGenerator_Php_Docblock(array(
               'shortDescription'       => $module . ' exception',
               'longDescription'        => 'This exception file was generated with Digitalus Framework Developer Tools',
                'tags'  => array(
                    array('name' => 'author', 'description' => $config->author)
                )
        )));
        $exceptionPath = self::modulePath($module) . '/Exception.php';
        $exceptionFile = '<?php' . PHP_EOL .
            "require_once APPLICATION_PATH . '/modules/dig/Exception.php';" . PHP_EOL .
            $exception->generate();
        file_put_contents($exceptionPath, $exceptionFile);
        return 'Created exception class at: ' . $exceptionPath;
    }

    public static function createItemController($module, $controller, $config) {
        $controllerClass = new Zend_CodeGenerator_Php_Class();
        $controllerClass->setName(ucfirst($module) . '_' . ucfirst($controller) . 'Controller');
        $controllerClass->setExtendedClass('DigCms_Library_Item_Controller');
        $controllerClass->setDocblock(new Zend_CodeGenerator_Php_Docblock(array(
           'shortDescription'       => $module . ' ' . $controller,
           'longDescription'        => 'This controller class was generated with Digitalus Framework Developer Tools',
            'tags'  => array(
                array('name' => 'author', 'description' => $config->author)
            )
        )));
        $controllerClass->setMethod(array(
            'name'      => 'renderAction',
            'docBlock'  => new Zend_CodeGenerator_Php_Docblock(array(
                'shortDescription'       => 'Renders the ' . $controller . ' content type.',
            ))
        ));
        $controllerFilename = self::modulePath($module) . '/controllers/' . ucfirst($controller . 'Controller.php');
        $file = new Zend_CodeGenerator_Php_File(array('classes' => array($controllerClass)));
        $viewMessage = self::createView($module, $controller, 'render', $config);
        file_put_contents($controllerFilename, $file->generate());
        return 'Created controller class at: ' . $controllerFilename . ' / ' . $viewMessage;
    }

    public static function createView($module, $controller, $action, $config) {
        $filepath = self::modulePath($module) . '/views/scripts';
        $filter = new Zend_Filter_Word_CamelCaseToDash();
        $filepath .= '/' . $filter->filter($controller);
        if(!is_dir($filepath)) {
            mkdir($filepath);
        }
        $filepath .= '/' . $filter->filter($action) . '.phtml';

        $view = '<p>View Script for:</p>' .
            '<ul><li>Module: ' . $module . '</li>' .
            '<li>Controller: ' . $controller . '</li>' .
            '<li>Action: ' . $action . '</li></ul>' .
            '<p>Filepath: ' . $filepath . '</p>';
        file_put_contents($filepath, $view);
        return 'Created view script at: ' . $filepath;
    }

    public static function createForm($module, $form, $config) {
        $formClass = new Zend_CodeGenerator_Php_Class();
        $formClass->setName(ucfirst($module) . '_Form_' . ucfirst($form))
            ->setExtendedClass('DigCms_Form_Item')
            ->setDocblock(new Zend_CodeGenerator_Php_Docblock(array(
               'shortDescription'       => $module . ' ' . $form . ' form',
               'longDescription'        => 'This form was generated with Digitalus Framework Developer Tools',
                'tags'  => array(
                    array('name' => 'author', 'description' => $config->author)
                ))));
        if(isset($config->item->property)) {
            $controls = array();
            $filter = new Zend_Filter_Word_CamelCaseToSeparator(' ');
            foreach ($config->item->property->toArray() as $property => $value) {
                $controls[] = sprintf('$this->addElement("text", "%s", array(
                    "label"	    => "%s"));', $property, ucwords($filter->filter($property)));
            };
            $formClass->setMethod(array(
                'name'  => 'init',
                'docBlock'  => new Zend_CodeGenerator_Php_Docblock(array(
                    'shortDescription'       => 'Adds the custom controls to the base item form.',
                )),
                'body'  => implode(PHP_EOL, $controls)
            ));
        }
        $formPath = self::modulePath($module) . '/forms/' . ucfirst($form) . '.php';
        $formFile = '<?php' . PHP_EOL .
            "require_once APPLICATION_PATH . '/modules/digCms/forms/Item.php';" . PHP_EOL .
            $formClass->generate();
        file_put_contents($formPath, $formFile);
        return 'Created form class at: ' . $formPath;
    }

    public static function createModel($module, $model, $config) {
        $modelClass = new Zend_CodeGenerator_Php_Class();
        $modelClass->setName(ucfirst($module) . '_Model_' . ucfirst($model))
            ->setExtendedClass('DigCms_Model_Item')
            ->setDocblock(new Zend_CodeGenerator_Php_Docblock(array(
               'shortDescription'       => $module . ' ' . $model . ' model',
               'longDescription'        => 'This model was generated with Digitalus Framework Developer Tools',
                'tags'  => array(
                    array('name' => 'author', 'description' => $config->author)
                ))));
        if(isset($config->item->property)) {
            $properties = array();
            foreach ($config->item->property->toArray() as $property => $value) {
                $properties[] = array(
                    'name'          => $property,
                    'visibility'    => 'public',
                    'defaultValue'  => $value
                );
            };
            $modelClass->setProperties($properties);
        }
        $modelPath = self::modulePath($module) . '/models/' . ucfirst($model) . '.php';
        $modelFile = '<?php' . PHP_EOL .
            "require_once APPLICATION_PATH . '/modules/digCms/models/Item.php';" . PHP_EOL .
            $modelClass->generate();
        file_put_contents($modelPath, $modelFile);
        return 'Created model class at: ' . $modelPath;
    }

    public static function createService($module, $service) {
        
    }

    public static function templatePath() {
        return APPLICATION_PATH . '/../templates';
    }
}
?>
